import axios from 'axios'
import { Message } from 'element-ui';
import store from '@/store'
import router from '@/router';
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    let token = store.state.user.token
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = 'application/json;charset=utf-8';
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      // 1. 跳转到登录
      router.push('/login')
      // 2. 清空用户数据
      store.commit('user/clearToken')
    }
    Message.error(error.response.data.msg)
    return Promise.reject(error)
  }
)

export default service
